"""
API网关统一主应用
================

基于RedFire框架的统一API网关应用
消除架构不一致，提供清晰的单一入口点
"""

import os
import sys
import asyncio
import logging
from pathlib import Path
from contextlib import asynccontextmanager
from typing import Dict, Any

# 添加项目根目录到路径
current_dir = Path(__file__).parent
project_root = current_dir.parent.parent.parent.parent
sys.path.insert(0, str(project_root))

import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

# 导入RedFire框架
from backend.redfire_framework.logging.manager import configure_logging

# 导入应用组件
from .config import get_api_gateway_config, validate_api_gateway_config
from .routes import create_gateway_routes, create_api_routes
from .dependencies import reset_services, get_container

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

# 全局配置实例
config = None


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    global config
    
    try:
        # 启动时初始化
        logger.info("🚀 启动API Gateway应用...")
        
        # 加载配置
        environment = os.getenv("GATEWAY_ENVIRONMENT", "development")
        config = get_api_gateway_config(environment)
        
        # 验证配置
        is_valid, errors = validate_api_gateway_config(config)
        if not is_valid:
            logger.error(f"配置验证失败: {errors}")
            raise RuntimeError(f"Configuration validation failed: {errors}")
        
        # 配置日志
        configure_logging(config.logging)
        
        # 初始化容器（触发依赖注入）
        container = await get_container()
        logger.info("依赖注入容器初始化完成")
        
        logger.info(f"✅ API Gateway启动成功 (环境: {environment})")
        
        yield
        
    except Exception as e:
        logger.error(f"❌ API Gateway启动失败: {e}", exc_info=True)
        raise
    finally:
        # 关闭时清理
        logger.info("🔄 正在关闭API Gateway...")
        reset_services()
        logger.info("✅ API Gateway关闭完成")


def create_app() -> FastAPI:
    """
    创建FastAPI应用实例
    
    Returns:
        FastAPI: 应用实例
    """
    # 创建应用
    app = FastAPI(
        title="RedFire API Gateway",
        description="基于RedFire框架的统一API网关",
        version="1.0.0",
        lifespan=lifespan,
        docs_url="/docs",
        redoc_url="/redoc",
        openapi_url="/openapi.json"
    )
    
    # 添加CORS中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 在生产环境中应该限制
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # 全局异常处理
    @app.exception_handler(Exception)
    async def global_exception_handler(request: Request, exc: Exception):
        """全局异常处理器"""
        logger.error(f"Unhandled exception: {exc}", exc_info=True)
        return JSONResponse(
            status_code=500,
            content={
                "error": "Internal Server Error",
                "message": "An unexpected error occurred",
                "path": str(request.url.path)
            }
        )
    
    # 添加路由
    gateway_router = create_gateway_routes()
    api_router = create_api_routes()
    
    app.include_router(api_router)
    app.include_router(gateway_router)  # 网关路由放在最后，作为fallback
    
    return app


# 创建应用实例
app = create_app()


def run_server():
    """运行服务器"""
    # 从环境变量或配置获取服务器参数
    host = os.getenv("GATEWAY_HOST", "0.0.0.0")
    port = int(os.getenv("GATEWAY_PORT", "8000"))
    debug = os.getenv("GATEWAY_DEBUG", "true").lower() == "true"
    reload = os.getenv("GATEWAY_RELOAD", "true").lower() == "true"
    
    logger.info(f"启动服务器: {host}:{port} (debug={debug}, reload={reload})")
    
    uvicorn.run(
        "backend.services.api-gateway.app.main:app",
        host=host,
        port=port,
        reload=reload,
        log_level="info" if not debug else "debug",
        access_log=True
    )


if __name__ == "__main__":
    run_server()
